package cn.codexin.wechatofficial.service;

import cn.codexin.wechatofficial.dto.ButtonDTO;
import cn.codexin.wechatofficial.dto.MenuDTO;
import cn.codexin.wechatofficial.mapper.HTDB.dbo.MenuMapper;
import cn.codexin.wechatofficial.model.dbo.Menu;
import cn.codexin.wechatofficial.model.dbo.MenuExample;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

/**
 * Created by xinGao 2020/4/23
 */
@Service
public class MenuService {

    @Autowired
    private MenuMapper menuMapper;


    public MenuDTO getMenuDTO() {
        MenuDTO menuDTO = new MenuDTO();
        List<ButtonDTO> buttonDTOS = new ArrayList<>();

        MenuExample getFirstLevelButton = new MenuExample();
        //获取一级菜单
        getFirstLevelButton.createCriteria()
                .andLevelEqualTo(1);
        //按照num 对菜单排序
        getFirstLevelButton.setOrderByClause("num");
        List<Menu> buttons = menuMapper.selectByExample(getFirstLevelButton);

        for (Menu button : buttons) {
            ButtonDTO buttonDTO = new ButtonDTO();
            //设置属性
            copyProperties(button, buttonDTO);
            //通过一级菜单获取二级菜单
            MenuExample getSecondLevelButton = new MenuExample();
            getSecondLevelButton.createCriteria()
                                .andLevelEqualTo(2)
                                .andParentEqualTo(button.getId());
            getSecondLevelButton.setOrderByClause("num");
            List<Menu> subButtons = menuMapper.selectByExample(getSecondLevelButton);
            List<ButtonDTO> subButtonDTOs = new ArrayList<>();
            for (Menu subButton : subButtons) {
                ButtonDTO subButtonDTO = new ButtonDTO();
                copyProperties(subButton, subButtonDTO);
                subButtonDTOs.add(subButtonDTO);
            }
            //如果子菜单不为空 就给相应的一级菜单添加子菜单
            if(subButtonDTOs.size() != 0)
                buttonDTO.setSub_button(subButtonDTOs.toArray(new ButtonDTO[subButtonDTOs.size()]));
            //将一级菜单加入一级菜单集中
            buttonDTOS.add(buttonDTO);
        }
        menuDTO.setButton(buttonDTOS.toArray(new ButtonDTO[buttonDTOS.size()]));
        return menuDTO;

    }

    public void copyProperties(Menu from, ButtonDTO to){
        //复制属性
        Objects.requireNonNull(from);
        Objects.requireNonNull(to);

        to.setUrl(from.getViewUrl());
        to.setName(from.getName());
        to.setType(from.getType());
        to.setKey(from.getClickKey());
        to.setMediaId(from.getMediaId());

    }
}
